package info.xiao.dataStructrue.array;

import java.util.*;

/**
 * @Classname ThreeSum  三数之和
 * @Description 链接: https://leetcode.cn/problems/3sum/
 * @Date 2022/9/27 14:09
 * @Created by 晓龙Oba
 */
public class ThreeSum {
    public static void main(String[] args) {
        int[] nums = {-2, 0, 0, 2, 2};// -4 -1 -1  0 1 2
        List<List<Integer>> result = threeSum(nums);
        System.out.println(result);
    }

    /*双指针*/
    private static List<List<Integer>> threeSum(int[] nums) {
        ArrayList<List<Integer>> lists = new ArrayList<>();
        Map<String, Boolean> duplicate = new HashMap<>();

        /*第一步 排序*/
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2 && nums[i] < 1; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            Integer leftIndex = i + 1;
            Integer rightIndex = nums.length - 1;

            while (leftIndex < rightIndex) {
                if (nums[i] + nums[rightIndex] + nums[leftIndex] == 0 && duplicate.get("" + nums[i] + nums[rightIndex] + nums[leftIndex]) == null) {
                    ArrayList<Integer> integers = new ArrayList<>();
                    integers.add(nums[i]);
                    integers.add(nums[leftIndex]);
                    integers.add(nums[rightIndex]);
                    lists.add(integers);
                    duplicate.put("" + nums[i] + nums[rightIndex] + nums[leftIndex], true);
                    leftIndex++;
                    rightIndex--;
                    continue;
                } else if (nums[i] + nums[rightIndex] + nums[leftIndex] > 0) {
                    rightIndex--;
                    continue;
                } else {
                    leftIndex++;
                }
            }
        }
        return lists;
    }
}
